package com.sonix.app;

import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;

import com.google.gson.Gson;
import com.sonix.base.BeiDot;
import com.sonix.util.DownloadUtil;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class Api {

    public static String upHost = "https://spi.zhilun.co/spi";

    public final static String BG_DOWNLOAD_SUCCESS = "BG_DOWNLOAD_SUCCESS";

    public static final String BG_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/beibi/"; //绘制数据保存目录

    private static final String TAG = "Api";

    public synchronized static void uploadDots(List<BeiDot> tmpDots) {
        if (tmpDots.size() > 0) {
            Gson gson = new Gson();
            String dotStr = gson.toJson(tmpDots);
            MediaType mediaType = MediaType.get("application/json; charset=utf-8");
            String requestBody = dotStr;
            Request request = new Request.Builder()
                    .url(upHost + "/dot/save")  //120.55.39.10  //192.168.3.74
                    .post(RequestBody.create(mediaType, requestBody))
                    .build();
            OkHttpClient okHttpClient = new OkHttpClient();
            okHttpClient.newCall(request).enqueue(new Callback() {
                public void onFailure(Call call, IOException e) {
                    Log.d(TAG, "onFailure: " + e.getMessage());
                }

                public void onResponse(Call call, Response response) throws IOException {
                    Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());
                    Headers headers = response.headers();
                    for (int i = 0; i < headers.size(); i++) {
                        Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                    }
                    Log.d(TAG, "onResponse: " + response.body().string());
                }
            });
        }
    }

    public static void downloadBg(int bookID, int pageID, Context ctx) {
        final String pngFile = BG_PATH +bookID+"_"+pageID+".png";

        DownloadUtil.get().download(upHost + "/bg/download?bookId=" + bookID +"&pageId="+ pageID, pngFile,
                new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess() {
                Log.d(TAG, "onResponse:下载成功" );
                Intent intent = new Intent(BG_DOWNLOAD_SUCCESS);
                intent.putExtra("pnfFile", pngFile);
                ctx.sendBroadcast(intent);
            }

            @Override
            public void onDownloading(int progress) {

            }

            @Override
            public void onDownloadFailed() {

            }
        });
    }
}
